<template>
    <layout-nav>
        <Tabs :data-source="typeList" class-pre="type" :value.sync="type" />
        <div class="chart-wrapper" ref="chartWrapper">
            <chart class="chart" :options="chartOptions" />
        </div>
        <div v-if="groupList.length > 0">
            <ol>
                <li v-for="group in groupList" :key="group.title">
                    <h3 class="title">
                        {{ beautify(group.title) }}
                        <span>￥{{ group.total }}</span>
                    </h3>
                    <ol>
                        <li v-for="item in group.items" :key="item.createdAt" class="record">
                            <span>{{ tagString(item.tags) }}</span>
                            <span class="notes">{{ item.notes }}</span>
                            <span>￥{{ item.amount }}</span>
                        </li>
                    </ol>
                </li>
            </ol>
        </div>
        <div v-else class="noresult">
            <iconNav name="nodata" class="nodata" />
            <p>快去记一笔吧！</p>
        </div>
    </layout-nav>
</template>

<script lang="ts">
import layoutNav from '../components/layoutNav.vue'
import Vue from 'vue';
import { Component } from 'vue-property-decorator';
import Tabs from '@/components/Tabs.vue';
import intervalList from '@/constants/intervalList';
import typeList from '@/constants/typeList';
import dayjs from 'dayjs'
import clone from '../lib/clone';
import iconNav from '@/components/iconNav.vue';
import Chart from '@/components/Chart.vue'
import _ from 'lodash'
@Component({
    components: { layoutNav, Tabs, Chart },
})
export default class Statistics extends Vue {
    get chartOptions() {
        const today = new Date();
        const chartDataList = []
        for(let i = 0; i <= 29;i++){
            const dateString = dayjs(today).subtract(i,'day').format("YYYY-MM-DD")
            chartDataList.push({key:dateString,value: _.find(this.groupList,{title:dateString})?.total || 0})
        }  
        chartDataList.sort((a,b) => {
            if(a.key > b.key){
                return 1
            }else if(a.key === b.key) {
                return 0
            }else {
                return -1
            }
        })
        const keys = chartDataList.map(item => item.key)
        const values = chartDataList.map(item => item.value)
        
        return {
            grid: {
                left: 0,
                right: 0,
            },
            xAxis: {
                type: 'category',
                data: keys,
                axisTick: { alignWithLabel: true },
                axisLine: { lineStyle: { color: '#666' } },
                axisLabel: {
                    formatter: function (value:string,index:number) {
                        return value.substring(5)
                    }
                }
            },
            yAxis: {
                type: 'value',
                show: false
            },
            series: [{
                symbol: 'circle',
                symbolSize: 12,
                itemStyle: { borderWidth: 1, color: '#666', borderColor: '#666' },
                data:values,
                type: 'line'
            }],
            tooltip: {
                show: true, triggerRef: 'click',
                position: 'top',
                formatter: '{c}'
            }
        };
    }

    get recordList() {
        return (this.$store.state as RootState).recordList
    }
    get groupList() {
        const { recordList } = this;
        const recordSorted = clone(recordList)
            .filter(r => r.type === this.type)
            .sort((a, b) => dayjs(b.createdAt).valueOf() - dayjs(a.createdAt).valueOf())
        if (recordSorted.length === 0) { return [] }
        type RenderList = { title: string, total?: number, items: RecordItem[] }[]
        const renderList: RenderList = [{ title: dayjs(recordSorted[0].createdAt).format('YYYY-MM-DD'), items: [recordSorted[0]] }]
        for (let i = 1; i < recordSorted.length; i++) {
            const current = recordSorted[i]
            const last = renderList[renderList.length - 1]
            if (dayjs(last.title).isSame(dayjs(current.createdAt), 'day')) {
                last.items.push(recordSorted[i])
            } else {
                renderList.push({ title: dayjs(recordSorted[i].createdAt).format('YYYY-MM-DD'), items: [recordSorted[i]] })
            }
        }
        renderList.forEach(group => {
            group.total = group.items.reduce((sum, item) => sum + item.amount, 0)
        })
        return renderList
    }
    tagString(tags: string[]) {
        return tags.length === 0 ? '无' : tags.join(',')
    }
    mounted() {
        (this.$refs.chartWrapper as HTMLDivElement).scrollLeft = 9999;
    }
    beautify(string: string) {
        const day = dayjs(string)
        const now = dayjs()
        if (day.isSame(now, 'day')) {
            return '今天'
        } else if (day.isSame(now.subtract(1, 'day'), 'day')) {
            return '昨天'
        } else if (day.isSame(now.subtract(2, 'day'), 'day')) {
            return '前天'
        } else if (day.isSame(now, 'year')) {
            return day.format('M月D日')
        } else {
            return day.format('YYYY年M月D日')
        }
    }
    created() {
        this.$store.commit('fetchRecords')
    }
    type = '-';
    interval = 'day'
    intervalList = intervalList
    typeList = typeList
}
</script>

<style scoped lang="scss">
::v-deep {
    .type-type-item {
        background: #c4c4c4;

        &.selected {
            background: white;

            &::after {
                display: none;
            }
        }
    }

    li.interval-type-item {
        height: 48px;
    }
}
</style>
<style lang="scss" scoped>
.echarts {
    max-width: 100%;
    height: 400px;
}

.chart {
    width: 430%;
    
    &-wrapper {
        overflow: auto;

        &::-webkit-scrollbar {
            display: none;
        }
    }
}

%item {
    padding: 8px 16px;
    line-height: 24px;
    display: flex;
    justify-content: space-between;
    align-content: center;
}

.title {
    @extend %item;
}

.record {
    background: white;
    @extend %item;
}

.notes {
    margin-right: auto;
    margin-left: 16px;
    color: #999;
}

.noresult {
    display: flex;
    align-items: center;
    min-height: calc(100vh - 110px);
    flex-direction: column;

    .nodata {
        font-size: 150px;
    }
}
</style>